package br.ucb.sirad.services;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
 *
 * @author Eliangela
 */
public class XlsFile {
 
    private OutputStream arqSaida;
    private HSSFWorkbook workbook;
    private HSSFSheet principalSheet;
    private List<String[]> lista = new ArrayList<String[]>();
    public XlsFile(String nomePlanilha, String arqSaida) throws IOException {
        this.arqSaida = new FileOutputStream(arqSaida);
        workbook = new HSSFWorkbook();
        principalSheet = workbook.createSheet(nomePlanilha);
    }
 
    public XlsFile(String arqSaida) throws IOException {
        this("sheet1", arqSaida);
    }
 
    public void writeLine(String... dados) throws IOException {
        lista.add(dados);
    }
 
    public void array2ExcelTable(String[][] dados) throws IOException {
        lista.addAll(Arrays.asList(dados));
    }
 
    public void close() throws IOException {
        flush();
        arqSaida.close();
    }
 
    private void flush() throws IOException {
        String dados[] = null;
        for (int linha = 0; linha < lista.size(); linha++) {
            dados = lista.get(linha);
            HSSFRow row = principalSheet.createRow(linha);
            for (int col = 0; col < dados.length; col++) {
                String s = dados[col];
                HSSFCell cell = row.createCell(col);
                cell.setCellValue(s);
            }
        }
        workbook.write(arqSaida);
        arqSaida.flush();
 
        lista = new ArrayList<String[]>();
    }
 
}
